package com.ccloud.blog.modules.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccloud.blog.modules.blog.domain.Blog;
import com.ccloud.blog.modules.blog.domain.BlogTag;
import com.ccloud.blog.modules.blog.service.IBlogService;
import com.ccloud.blog.modules.blog.service.IBlogTagRelationService;
import com.ccloud.blog.modules.blog.warpper.BlogWarpper;
import com.ccloud.common.core.model.LoginVal;
import com.ccloud.common.core.reqres.response.R;
import com.ccloud.common.core.utils.ConstantUtils;
import com.ccloud.common.core.utils.OauthUtils;
import com.ccloud.common.core.utils.text.SubUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @author chentl
 * @version V1.0
 * @Project BlogController
 * @Title BlogController.java
 * @Description blog 控制器
 * @Package com.echo.blog.business.blog.controller
 * @date 2019/9/5 18:03
 * @Copyright: 上海顺益信息科技有限公司 All rights reserved.
 */
@RestController
@Slf4j
@RequestMapping("/blogInfo")
public class BlogController {

    @Value("${file.dfsPath}")
    public String FILE_URL;

    @Resource
    private IBlogService blogService;

    @Resource
    private IBlogTagRelationService tagRelationService;

    @RequestMapping(value = "/blogList")
    public R getBlogList(Blog blog) {
        Page<Map<String, Object>> page = new Page<>();
        page.setSize(10);
        page.setCurrent(1);
        List<Map<String, Object>> list = new BlogWarpper(blogService.getBlogList(page, blog, "order")).wrap();

        page.setRecords(list);
        return R.ok(page);
    }

    @RequestMapping(value = "/getBlogsByType")
    public R getBlogsByTypeId(@RequestParam("blogType") Integer blogType) {
        if (blogType == null) {
            return R.fail("参数为空");
        }
        List<Map<String, Object>> list = new BlogWarpper(blogService.getBlogsByBlogTypeId(blogType)).wrap();
        return R.ok(list, "分类博客列表成功");
    }

    @RequestMapping(value = "/add")
    public R add(Blog blog) {
        if (blog == null) {
            return R.fail("博客对象为空");
        }
        LoginVal loginVal = OauthUtils.getCurrentUser();

        Integer loginId = loginVal.getIntegerUserId();
        blog.setCreateBy(loginId);
        blog.setUpdateBy(loginId);
        blog.setAuthor(loginId);
        blog.setBlogContent("");
        boolean flag = blogService.save(blog);
        if (flag) {
            return R.ok("新建文章成功");
        } else {
            return R.fail("新建文章失败");
        }
    }

    @RequestMapping(value = "/delete")
    public R delete(Blog blog) {
        if (blog == null) {
            return R.fail("博客对象为空");
        }
        //删除文章
        blogService.removeById(
                blog.getId());
        //同时删除关联关系
        tagRelationService.deleteByBlogId(blog.getId());
        return R.ok(null, "文章删除成功~");
    }

    @RequestMapping(value = "/update")
    public R update(Blog blog) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (blog == null) {
            return R.fail("博客对象为空");
        }
        Integer blogId = blog.getId();
        String content = blog.getBlogContent();
        String matchUrl = SubUtil.getSubUtilSimple(content, ".*?\\]\\((.*?)\\).*?");
        String imgUrl = StringUtils.isEmpty(matchUrl) ? "https://picsum.photos/500/300" : matchUrl;
        try {
            List<BlogTag> tags = JSONObject.parseObject(blog.getBlogTagList(), new TypeReference<List<BlogTag>>() {
            });
            if (CollectionUtils.isNotEmpty(tags)) {
                //重建关联
                tagRelationService.rebuildBlogTagRelation(tags, blogId);
            }
            //1 已发布 0 未发布 这里是已发布
            blog.setIsPublished(ConstantUtils.Public.ONE);
            blog.setCoverUrl(imgUrl);
            //更新博客
            boolean flag = blogService.updateById(blog);
            Blog blogDb = blogService.getById(blogId);
            if (flag) {
                return R.ok(tags, "发布成功~");
            } else {
                log.error("更新博客失败，无法为id为{}的博客建立索引", blog.getId());
                return R.fail("更新博客失败，无法为博客建立索引~");
            }


        } catch (Exception e) {
            log.error("博客标签json解析时出错 ", e);
            return R.fail("博客标签json解析时出错");
        }
    }

    @RequestMapping(value = "/getRecommendedArticle")
    public R getRecommendedArticle(Blog blog) {
        List<Map<String, Object>> list = blogService.getRecommendedArticle(blog);
        return R.ok(list, "发布成功~");
    }

    @RequestMapping(value = "/uploadImage")
    public R uploadImage(@RequestParam(value = "image", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        if (file != null) {
            byte[] bytes = null;
            try {
                bytes = file.getBytes();
            } catch (IOException e) {
                log.error("获取文件字节流失败", e);
            }
            //todo 重写上传
            //执行上传
//            String imagePath = FILE_URL + FastDFSUtils.uploadPic(bytes, file.getOriginalFilename(), file.getSize());
            return R.ok("", "上传图片成功");
        }

        return R.fail(null, "上传图片失败");
    }


}
